// 例4-9 读取并显示文件属性
// myls.c
#include <sys/stat.h>
#include <stdio.h>
#include <string.h>

void mode_to_letter(mode_t mode, char *str) { 
    strcpy(str, "--------"); 
    if (S_ISDIR(mode)) str[0] = 'd'; 
    if (S_ISCHR(mode)) str[0] = 'c'; 
    if (S_ISBLK(mode)) str[0] = 'b'; 
    if (mode & S_IRUSR) str[1] = 'r'; 
    if (mode & S_IWUSR) str[2] = 'w';
    if (mode & S_IXUSR) str[3] = 'x';
    if (mode & S_IRGRP) str[4] = 'r'; 
    if (mode & S_IWGRP) str[5] = 'w';
    if (mode & S_IXGRP) str[6] = 'x';
    if (mode & S_IROTH) str[7] = 'r'; 
    if (mode & S_IWOTH) str[8] = 'w'; 
    if (mode & S_IXOTH) str[9] = 'x';
}

void do_ls(char *pathname) { 
    struct stat attr; 
    char mode[11]; 
    if (stat(pathname, &attr) != -1) {
        mode_to_letter(attr.st_mode, mode); 
        printf("file %s mode is: %s\n", pathname, mode);
    }
    else {
        printf("Stat error\n");
        exit(1);
    }
}

int main(int argc, char **argv) {
    if (argc < 2) { 
        printf("usage: myls filename \n");
        exit(1);
    }
    do_ls(argv[1]);
    return 0;
}
